<template>
  <div>
    <el-dialog :close-on-click-modal='false' v-drag :title="type === 'edit'?$t('编辑'):$t('添加')" v-if="dialogVisible" :visible.sync="dialogVisible" width="620px" top="10vh" @close='close'>
      <div class="dialogContentBox">
        <el-form ref="form" :model="record" label-width="110px" :rules="rules" label-position="left" inline style="margin:0 30px;">
          <el-form-item :label="$t('名称')" prop="name">
            <el-input v-emoji v-model="record.name" ref="diyName" style="width:400px;" size='small'></el-input>
          </el-form-item>
          <el-form-item :label="$t('报表周期')" prop="period">
            <el-radio-group v-model="record.period" @change="periodChange">
              <el-radio label="single" class="single">{{$t('历史报表')}}</el-radio>
              <el-radio label="loop" class="loop">{{$t('周期性报表')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="time_type">
            <el-select size="small" v-model="record.time_type" ref="diyInterval" placeholder="" :disabled='record.period !=="loop"' style="width:150px;margin-left:19px" @change="intervalChange">
              <el-option v-for="item in intervalList" :key="item.value" :label="$t(item.label)" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- ----------------------------------single----------------------------- -->
          <el-form-item :label="$t('自定义时间')" prop="time" v-if="record.period === 'single'">
            <el-date-picker v-model="record.time" size="small" style="width:400px;" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" :range-separator="$t('至')" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <!-- ----------------------------------day----------------------------- -->
          <el-form-item :label="$t('自定义时间')" prop="time" v-if="record.time_type === 'day'">
            <el-time-picker size="small" is-range v-model="record.time" style="width:400px;" value-format="HH:mm:ss" :range-separator="$t('至')" :start-placeholder="$t('开始时间')" :end-placeholder="$t('结束时间')" :placeholder="$t('选择时间范围')">
            </el-time-picker>
          </el-form-item>
          <!-- ----------------------------------week----------------------------- -->
          <el-form-item :label="$t('自定义时间')" prop="from_time" v-if="record.time_type === 'week'">
            <el-select size="small" v-model="record.from_time" ref="diyFromTimeWeek" :placeholder="$t('请选择日期')" style="width:185px;">
              <el-option v-for="item in weekList" :key="item.value" :label="$t(item.label)" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="to_time" v-if="record.time_type === 'week'">
            <el-select size="small" v-model="record.to_time" ref="diyToTimeWeek" :placeholder="$t('请选择日期')" style="width:185px;margin-left:16px;">
              <el-option v-for="item in weekList" :key="item.value" :label="$t(item.label)" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- ----------------------------------month----------------------------- -->
          <el-form-item :label="$t('自定义时间')" prop="from_time" v-if="record.time_type === 'month'">
            <el-select size="small" v-model="record.from_time" ref="diyFromTimeMonth" :placeholder="$t('请选择日期')" style="width:185px;">
              <el-option v-for="item in monthList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="to_time" v-if="record.time_type === 'month'">
            <el-select size="small" v-model="record.to_time" ref="diyToTimeMonth" :placeholder="$t('请选择日期')" style="width:185px;margin-left:16px;">
              <el-option v-for="item in monthList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('自定义模板')" prop="reftemplate">
            <el-select v-model="record.reftemplate" ref="diyTemplateName" multiple clearable filterable style="width:400px;" @change="changeSelect" size='small'>
              <!-- <div class="selectBox">
                <el-checkbox v-model="checked" :indeterminate="isIndeterminate" @change='selectAll' class="selectAll">{{$t('全选')}}</el-checkbox>
                <el-link :underline="false" @click='selectRe' class="selectRe" style="line-height: 19px;padding-left:20px;">{{$t('反选')}}</el-link>
              </div> -->
              <el-option v-for="item in templateList" :key="item.name" :label="item.show_name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
        <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
      </span>
    </el-dialog>
    <warningTools :dialogVisible="dialogVisibleTool" :msg="msg" @visibleSubmit="visibleSubmit" />
  </div>
</template>
<script>
import { addReport, editReport } from '@/api/system/logReport/diyReport'
import { getTemplateArray } from '@/api/system/logReport/templateReport'
import { inputClass, selectClass } from '@/utils/input-class.js'
import warningTools from "@/components/warningTools/index";
export default {
  name: 'DiyReportTools',
  components:{
    warningTools
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim() || !value) {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateTemplateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateInterval = (rule, value, callback) => {
      if (this.record.period === 'loop' && !String(value).trim()) {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    return {
      dialogVisibleTool:false,
      msg:'',
      dialogVisible: false,
      record: {
        name: '',
        period: 'single',
        time_type: '',
        time: '',
        from_time: '',
        to_time: '',
        reftemplate: [],
        reftemplate: []
      },
      recordTemp:{},
      recordCopy: {
        name: '',
        period: 'single',
        time_type: '',
        time: '',
        from_time: '',
        to_time: '',
        reftemplate: [],
        reftemplate: []
      },
      pickerOptions: {
        disabledDate: (time) => {
          return Date.now() < time.getTime()
        }
      },
      templateList: [],
      templateListAll: [],
      checked: false,
      isIndeterminate: false,
      type: null,
      intervalList: [
        { value: 'day', label: '日' },
        { value: 'week', label: '周' },
        { value: 'month', label: '月' }
      ],
      weekList: [
        { value: '1', label: '星期一' },
        { value: '2', label: '星期二' },
        { value: '3', label: '星期三' },
        { value: '4', label: '星期四' },
        { value: '5', label: '星期五' },
        { value: '6', label: '星期六' },
        { value: '7', label: '星期日' }
      ],
      monthList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        time_type: [{ required: false, validator: validateInterval, trigger: 'blur' }],
        time: [{ required: false, validator: validateName, trigger: 'blur' }],
        from_time: [{ required: false, validator: validateName, trigger: 'blur' }],
        to_time: [{ required: false, validator: validateName, trigger: 'blur' }],
        reftemplate: [{ required: false, validator: validateTemplateName, trigger: 'change' }]
      }
    }
  },
  watch: {
    'record.time_type' (val) {
      if (val === 'week') {
        this.$nextTick(() => {
          const selectData = ['diyFromTimeWeek', 'diyToTimeWeek']
          selectClass(this.$refs, selectData)
        })
      } else if (val === 'month') {
        this.$nextTick(() => {
          const selectData = ['diyFromTimeMonth', 'diyToTimeMonth']
          selectClass(this.$refs, selectData)
        })
      }
    }
  },
  methods: {
    init (type,data) {
      this.type = type
      this.dialogVisible = true
      getTemplateArray().then(res => {
        if (res.status === 0) {
          this.templateList = res.info
          this.templateListAll = []
          this.templateList.forEach(item => {
            this.templateListAll.push(item.name)
          })
        }
      })
      this.$nextTick(() => {
        const dataEdit = ['diyName']
        const selectDataEdit = ['diyInterval', 'diyTemplateName']
        inputClass(this.$refs, dataEdit)
        selectClass(this.$refs, selectDataEdit)
      })
      if (data) {
        this.record.name = data.name
        if (data.time_type === 'single') {
          this.record.period = data.time_type
          this.record.time = [data.from_time, data.to_time]
        } else {
          this.record.period = 'loop'
          this.record.time_type = data.time_type
          if (this.record.time_type === 'day') {
            this.record.time = [data.from_time, data.to_time]
          } else {
            this.record.from_time = data.from_time
            this.record.to_time = data.to_time
          }
        }
        this.record.reftemplate = data.reftemplate
        this.record.reftemplate = data.reftemplate
        this.recordTemp = JSON.parse(JSON.stringify(this.record))
      }
    },
     visibleSubmit() {
      this.dialogVisibleTool = false;
      this.msg = "";
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.record.port = Number(this.record.port)
          let formData = JSON.parse(JSON.stringify(this.record))
          if (formData.period === 'single' || formData.time_type === 'day') {
            formData.from_time = formData.time[0]
            formData.to_time = formData.time[1]
          }
          if (this.type === 'edit') {
            const params = {
              old_form:JSON.stringify(this.recordTemp),
              new_form:JSON.stringify(formData),
            }
            editReport(params).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('编辑成功'))
                this.close()
                this.$parent.listData()
              }
            }).catch(err=> {
              if (err.status === -1000) {
                this.dialogVisibleTool = true;
                this.msg = err.msg || "";
              }
            })
          } else {
            const params = {
             ...formData,
             reftemplate:JSON.stringify(formData.reftemplate)
            }
            console.log('params',params)
            addReport(params).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('添加成功'))
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    periodChange () {
      this.record.time = ''
      this.record.from_time = ''
      this.record.to_time = ''
      if (this.record.period === 'single') {
        this.record.time_type = ''
      } else {
        this.record.time_type = 'day'
      }
    },
    intervalChange () {
      this.record.time = ''
      this.record.from_time = ''
      this.record.to_time = ''
    },
    close () {
      this.checked = false
      this.isIndeterminate = false
      this.dialogVisible = false
      this.type = null
      this.record = Object.assign({}, this.recordCopy)
      this.$nextTick(() => {
        if(this.$refs.form) {
          this.$refs.form.resetFields()
        }
      })
    },
    changeSelect (val) {
      let checkedCount = val.length
      if(checkedCount > 10) {
        this.record.reftemplate.splice(this.record.reftemplate.length-1,1);
        this.$messages.success(this.$t('模板数量已经超过最大值10个'))
      }
      this.checked = checkedCount === this.templateListAll.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.templateListAll.length
    },
    selectAll () {
      this.record.reftemplate = []
      if (this.checked) {
        this.templateList.forEach((item) => {
          if (item.enPortMode !== 3) {
            this.record.reftemplate.push(item.name)
          }
        })
      } else {
        this.record.reftemplate = []
      }
      this.isIndeterminate = false
    },
    selectRe () {
      let check_array = []
      for (let item of this.record.reftemplate) {
        if (item.enPortMode !== 3) {
          check_array.push(item)
        }
      }
      this.record.reftemplate = this.templateListAll.filter((x) => !check_array.some((item) => x === item))
      this.changeSelect(this.record.reftemplate)
    }
  }
}
</script>
<style scoped>
.dialogContentBox {
  max-height: calc(80vh - 184px);
  overflow-y: auto;
}
.selectBox {
  padding: 0 20px;
}
</style>
